<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetPage">
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('员工账号')" prop="accountNumber">
          <el-input v-model="page.accountNumber"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('员工姓名')" prop="adminName">
          <el-input v-model="page.adminName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')" prop="status">
          <el-select v-model="page.status" style="width: 100%;" clearable>
            <el-option :value="0" :label="$t('禁用')"></el-option>
            <el-option :value="1" :label="$t('启用')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[644]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in searchProductList" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label=" $t('角色类型')" prop="adminRole">
          <el-select style="width: 100%" v-model="page.adminRole" clearable>
            <el-option v-for="item in LowerRoleList" :label="item.name" :key="item.id"
                       :value="item.type"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[1159]">
        <el-form-item :label="$t('经理名称')">
          <el-select :placeholder="$t('请选择经理')" style="width: 100%"
                     v-model="page.managerId" clearable filterable>
            <el-option v-for="item in managerList" :key="item.adminUserId" :label="item.adminName"
                       :value="item.adminUserId"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label=" $t('创建时间')" prop="timeValue">
          <el-date-picker
              style="width: 100%"
              v-model="page.timeValue"
              value-format="yyyy-MM-dd"
              type="daterange"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card style="margin-top: 10px" shadow="never">
      <el-row style="text-align: right">
        <el-button v-show="$permiss[1160]" type="primary" @click="batchBindAPP">
          {{ $t('批量绑定APP') }}
        </el-button>
        <el-button v-show="$permiss[10]" type="primary" @click="addStaff">
          {{ $t('新增员工') }}
        </el-button>
      </el-row>
      <el-row style="margin-top: 10px">
        <!--        表格-->
        <Table :table-column="tableColumn" :loading="loading" :table-data="tableData" :page="page"
               @handleSizeChange="handleSizeChange"
               @handleCurrentChange="handleCurrentChange">
          <template slot="bindApp" slot-scope="{row}">
            <el-tooltip :content="row.list.join(' , ')">
              <div>
                <el-tag :disable-transitions="true" style="margin: 5px 5px 0 0" v-for="(item,index) in row.list"
                        v-show="index < 3" :key="item">
                  {{ item }}
                </el-tag>
              </div>
            </el-tooltip>
          </template>
          <template slot-scope="scope" slot="status">
            <el-switch :disabled="!$permiss[11]" @change="changeStatus(scope.row)"
                       :value="scope.row.status"></el-switch>
          </template>
          <template slot-scope="scope" slot="handle">
            <el-dropdown>
                   <span class="el-dropdown-link">
                     <el-link type="primary" :underline="false">{{ $t('操作') }}</el-link>
                   <i class="el-icon-arrow-down el-icon--right" style="color: #ff8a00;font-size: 12px"></i>
                 </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-show="$permiss[12]" @click.native="editStaff(scope.row)">{{
                    $t('编辑')
                  }}
                </el-dropdown-item>
                <el-dropdown-item v-show="$permiss[15]" @click.native="resetPassword(scope.row)">
                  {{ $t('重置密码') }}
                </el-dropdown-item>
                <el-dropdown-item v-show="$permiss[590] && scope.row.isOrder === 1"
                                  @click.native="upDateSingle(scope.row)">{{
                    scope.row.isSingle === 1 ? $t('禁止分单') : $t('开始分单')
                  }}
                </el-dropdown-item>
                <el-dropdown-item v-show="$permiss[17]" @click.native="bindApp(scope.row)">{{
                    $t('绑定APP')
                  }}
                </el-dropdown-item>
                <el-dropdown-item v-show="$permiss[800]" @click.native="unBindApp(scope.row)">{{
                    $t('解绑APP')
                  }}
                </el-dropdown-item>
                <el-dropdown-item v-show="$permiss[1510]" @click.native="unBindDevice(scope.row)">{{
                    $t('解绑设备号')
                  }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </Table>
      </el-row>
    </el-card>
    <Dialog @close="clearForm" :visible.sync="visibleStaff.visible" :title="visibleStaff.StaffTitle"
            @cancel="visibleStaff.visible = false" @confirm="confirm"
            width="50%"
    >
      <el-form :model="form" ref="form" :rules="rulesForm" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="$t('员工姓名')" prop="adminName">
              <el-input v-model="form.adminName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('手机号码')" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('坐席号')" prop="sipid">
              <el-input v-model="form.sipid"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('员工账号')" prop="accountNumber">
              <el-input v-model="form.accountNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('选择角色')" prop="adminRole">
              <el-select style="width: 100%" :disabled="visibleStaff.visibleType === 'edit'" v-model="form.adminRole"
                         @change="selectRoleChange">
                <el-option v-for="item in LowerRoleList" :key="item.type" :label="item.name"
                           :value="item.type"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('选择上级')" prop="managerId" v-if="roleAuth.visibility === 1">
              <el-select style="width: 100%" :disabled="visibleStaff.visibleType === 'edit'" v-model="form.managerId"
                         @change="selectMangChange">
                <el-option v-for="item in ManagerUserList" :label="item.adminName" :key="item.adminUserId"
                           :value="item.adminUserId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('选择APP')" v-if="roleAuth.isProduct === 1" prop="products">
              <el-checkbox-group v-model="form.products">
                <el-checkbox :disabled="visibleStaff.visibleType === 'edit'"
                             v-for="item in productList"
                             :key="item.productId"
                             :label="item.productName"
                             :value="item.productId"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Dialog>
    <Dialog @cancel="bindAppVisible = false" @confirm="bindAppConfirm" @close="clearForm" :visible.sync="bindAppVisible"
            :title="$t('绑定APP')"
            :close-on-click-modal="false" width="30%">
      <el-select v-model="bindAppValue" style="width: 100%">
        <el-option v-for="item in appList"
                   :label="item.productName"
                   :value="item.productName"
                   :key="item.productId"
        ></el-option>
      </el-select>
    </Dialog>
    <!--    解绑app-->
    <Dialog @cancel="unBindAppVisible = false" @confirm="unBindAppConfirm"
            :footer="$permiss[802] ? true : false"
            :visible.sync="unBindAppVisible"
            :title="$t('解绑APP')"
            :close-on-click-modal="false" width="30%">
      <el-checkbox-group v-model="unbindAppForm.productIds">
        <el-checkbox v-for="item in unBindProduct" :label="item.productId" :key="item.productId">
          {{ item.productName }}
        </el-checkbox>
      </el-checkbox-group>
    </Dialog>
    <!--    批量绑定APP-->
    <Dialog :visible.sync="batchBindVisible" width="55%" :title="$t('批量绑定APP')" @cancel="batchBindVisible = false"
            @confirm="batchConfirm" @close="batchClose"
    >
      <el-row :gutter="24">
        <el-form>
          <el-col :span="10" :xs="24">
            <el-form-item label-width="80px" :label="$t('APP名称')">
              <el-select v-model="batchAPPName">
                <el-option v-for="item in batchAPPList" :key="item.productId" :value="item.productName"
                           :label="item.appName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14" :xs="24" style="text-align: right">
            <el-button type="primary" @click="searchBatch">{{ $t('绑定经理/人员') }}</el-button>
          </el-col>
        </el-form>
      </el-row>
      <div style="margin-top: 20px">
        <el-row :gutter="24">
          <el-form label-width="80px">
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工姓名')">
                <el-input v-model="batchPage.adminName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item :label="$t('员工账号')">
                <el-input v-model="batchPage.accountNumber" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24" style="text-align: right">
              <el-button type="primary" @click="searchBatch" :disabled="!batchAPPName">{{ $t('查询') }}</el-button>
              <el-button @click="resetSearchBatch" :disabled="!batchAPPName">重置</el-button>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <el-table :data="batchTableData" max-height="400px" row-key="adminUserId" border
                :header-cell-style="{ backgroundColor: '#EFF6F9'}">
        <el-table-column type="select" width="55" align="center">
          <template slot="header">
            <el-checkbox @change="rowAllCheckChange($event)" :value="allSelectIsChecked"
                         :disabled="batchTableAllData.length === 0"
                         :indeterminate="rowSelectAll"></el-checkbox>
          </template>
          <template slot-scope="{row}">
            <el-checkbox :value="row.checked" :indeterminate="semiSelection(row)"
                         @change="rowCheckChange($event,row)"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column :label="$t('员工姓名')" prop="adminName"></el-table-column>
        <el-table-column :label="$t('员工账号')" prop="accountNumber" align="center"></el-table-column>
        <el-table-column :label="$t('角色名称')" prop="name" align="center"></el-table-column>
      </el-table>
    </Dialog>
  </div>
</template>

<script>
import qs from "qs";
import {dateFormatSection, deepClone} from "@/utils/tools";
import {
  fetchStaffList, updateSingle, resetPassword,
  selectManagerUser, bindingProduct, unbindProduct, unboundProduct,
  selectManager, updateStatusSystemUser,
  fetchLowerRole, searchBindProduct,
  addSystemUser, editSystemUser, batchBindProduct,
  selectProduct,
  unBindDevice
} from '@/api/system'

export default {
  name: 'staffManagement',
  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        timeValue: null,
      },
      visibleStaff: {
        visible: false,
        visibleType: '',
        StaffTitle: '',
      },
      tableData: [],
      ManagerUserList: [],
      LowerRoleList: [],
      searchProductList: [],
      productList: [],
      adminUserId: '',
      form: {
        adminName: '',
        accountNumber: '',
        managerId: '',
        adminRole: null,
        phone: '',
        isSingle: 1,
        sipid:null,
        products: [],
      },
      roleAuth: {
        isOrder: 0,
        isProduct: 0,
        visibility: 0,
      },
      tableColumn: [
        {label: this.$t('员工账号'), prop: 'accountNumber', align: 'center', minWidth: 100},
        {label: this.$t('员工姓名'), prop: 'adminName', align: 'center', minWidth: 100},
        {label: this.$t('坐席号'), prop: 'sipid', align: 'center', minWidth: 100},
        {label: this.$t('手机号码'), prop: 'phone', align: 'center', minWidth: 100},
        {label: this.$t('登录设备号'), prop: 'deviceId', align: 'center', minWidth: 100},
        {label: this.$t('角色名称'), prop: 'name', align: 'center', minWidth: 100},
        {label: this.$t('经理'), prop: 'managerName', align: 'center', minWidth: 100},
        {label: this.$t('已绑定APP'), align: 'center', slot: 'bindApp', minWidth: 250},
        {label: this.$t('创建人'), prop: 'inputName', align: 'center'},
        {label: this.$t('创建时间'), prop: 'creationTime', align: 'center', width: 150},
        {label: this.$t('状态'), slot: 'status', align: 'center', width: 100},
        {
          label: this.$t('操作'),
          slot: 'handle',
          align: 'center',
          width: 100,
          isHide: !this.$permiss[12] && !this.$permiss[15] && !this.$permiss[590] && !this.$permiss[17]
        },
      ],
      bindAppVisible: false,
      bindAppSelect: [],
      appList: [],
      bindAppValue: '',
      rulesForm: {
        adminName: [
          {required: true, message: this.$t('请输入员工姓名'), trigger: 'blur'}
        ],
        accountNumber: [
          {required: true, message: this.$t('请输入员工账号'), trigger: 'blur'},
          {min: 6, max: 15, message: this.$t('账号长度为6-15位'), trigger: 'blur'},
        ],
        adminRole: [
          {required: true, message: this.$t('请选择角色'), trigger: 'blur'}
        ],
        products: [
          {required: true, message: this.$t('请选择对象'), trigger: 'blur'}
        ],
        managerId: [
          {required: true, message: this.$t('请选择上级'), trigger: 'blur'}
        ],
      },
      unbindAppForm: {
        adminUserId: null,
        productIds: []
      },
      unBindProduct: [],
      unBindAppVisible: false,
      managerList: [],
      batchBindVisible: false,
      batchAPPList: [],
      batchAPPName: null,
      batchTableData: [],
      batchTableColumn: [
        {label: this.$t('员工账号'), prop: 'accountNumber', align: 'center'},
        {label: this.$t('角色名称'), prop: 'name', align: 'center'},
      ],
      batchPage: {},
      batchSelectRows: [],
      loading: false,
      batchTableAllData: [],
    }
  },
  mounted() {
    this.getTableData()
    this.getLowerRole()
    this.getSelect()
  },
  computed: {
    rowSelectAll() {
      const allCheck = this.batchTableAllData.every(item => item.checked)
      const allNoneCheck = this.batchTableAllData.every(item => !item.checked)
      // 半全选
      const semiCheck = this.batchTableAllData.some(item => item.checked)
      if (allCheck || allNoneCheck) {
        return false
      } else if (semiCheck && !allCheck && !allNoneCheck) {
        return true
      } else {
        return false
      }
    },
    allSelectIsChecked() {
      let flag
      const allNodeCheck = this.batchTableAllData.every(item => !item.checked)
      const semiCheck = this.batchTableAllData.some(item => !item.checked)
      if (allNodeCheck || semiCheck) {
        flag = false
      } else {
        flag = true
      }
      return flag
    }
  },
  methods: {
    async getTableData() {
      const timeValue = dateFormatSection(this.page.timeValue)
      const params = Object.assign({}, this.page, {
        datetimeStart: timeValue && timeValue.length > 1 ? timeValue[0] : undefined,
        datetimeEnd: timeValue && timeValue.length > 1 ? timeValue[1] : undefined,
      })
      delete params.timeValue
      this.loading = true
      const res = await fetchStaffList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.filter(item => {
          item.status = item.status === 1
          item.list = item.list || []
          return item
        })
        this.loading = false
        this.page = Object.assign({}, this.page, {
          total: total
        })
      }
    },
    async getSelect() {
      this.searchProductList = await selectProduct().then(res => res.data)
      this.getManagerList()
    },
    /*
    * 获取经理
    * */
    async getManagerList() {
      const res = await selectManager()
      if (res.code === 1) {
        this.managerList = res.data
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    dataChange(value) {
      if (value) {
        this.page.datetimeStart = value[0]
        this.page.datetimeEnd = value[1]
      } else {
        this.page.datetimeStart = ''
        this.page.datetimeEnd = ''
      }
    },
    async resetPassword(row) {
      this.$confirm(this.$t('确定重置密码?'), this.$t('提示'), {
        confirmButtonText: this.$t('确认'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(async () => {
        const {adminUserId} = row
        const res = await resetPassword({adminUserId: adminUserId})
        if (res.code === 1) {
          this.$message({
            type: 'success',
            message: this.$t('重置成功')
          });
        }
      });
    },
    // 绑定app
    async bindApp(row) {
      this.adminUserId = row.adminUserId
      const params = {
        adminUserId: this.adminUserId
      }
      const res = await unboundProduct(params)
      if (res.code === 1) {
        this.appList = res.data
        this.bindAppVisible = true
      }
    },
    // 解绑App
    async unBindApp({adminUserId}) {
      selectProduct({adminUserId: adminUserId, valid: 1}).then(res => {
        this.unBindProduct = res.data
        this.unbindAppForm.productIds = this.unBindProduct.map(i => i.productId)
        this.unbindAppForm.adminUserId = adminUserId
        this.unBindAppVisible = true
      })
    },
    // 解绑设备号
    unBindDevice({adminUserId}) {
      this.$confirm(this.$t('确认解绑') + '?', this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const formData = new FormData()
        formData.append('adminUserId', adminUserId)
        const res = await unBindDevice(formData)
        if (res.code === 1) {
          this.$message.success(this.$t('解绑成功'))
          this.unBindAppVisible = false
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    // 解绑app提交
    async unBindAppConfirm() {
      this.$confirm(this.$t('解绑后,历史记录保留,该员工将不再负责对应APP的业务,请谨慎操作') + '!', this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const {productIds, adminUserId} = this.unbindAppForm
        const unList = this.unBindProduct.filter(item => {
          // 过滤未绑定APP
          return productIds.indexOf(item.productId) === -1
        })
        const params = {
          productIds: unList.map(item => item.productId),
          adminUserId
        }
        const res = await unbindProduct(params)
        if (res.code === 1) {
          this.$message.success(this.$t('解绑成功'))
          this.unBindAppVisible = false
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    async bindAppConfirm() {
      const productList = this.appList.filter(i => i.productName === this.bindAppValue)
      const params = {
        adminUserId: this.adminUserId,
        productId: productList[0].productId,
        productName: productList[0].productName
      }
      const res = await bindingProduct(params)
      if (res.code === 1) {
        this.$message.success(this.$t('操作成功'))
        this.bindAppVisible = false
        this.getTableData()
      }
    },
    async upDateSingle(row) {
      const {adminUserId} = row
      const res = await updateSingle(qs.stringify({adminUserId: adminUserId}))
      if (res.code === 1) {
        this.$message({
          type: 'success',
          message: this.$t('操作成功')
        });
        this.getTableData()
      }
    },
    resetPage() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.getTableData()
    },
    async changeStatus(row) {
      const res = await updateStatusSystemUser(qs.stringify({
        adminUserId: row.adminUserId,
        status: row.status ? 0 : 1
      }))
      if (res.code === 1) {
        this.$message.success(this.$t('修改成功'))
        this.getTableData()
      }
    },
    async addStaff() {
      this.visibleStaff = {
        visible: true,
        visibleType: 'add',
        StaffTitle: this.$t('新增员工')
      }
    },
    async editStaff(row) {
      this.productList = await selectProduct({adminUserId: row.adminUserId, valid: 1}).then(res => res.data)
      this.visibleStaff = Object.assign({}, this.visibleStaff, {
        visible: true,
        visibleType: 'edit',
        StaffTitle: this.$t('编辑员工'),
      })
      this.form = Object.assign({}, this.form, {
        managerId: row.managerName,
        adminRole: row.type,
        adminName: row.adminName,
        phone: row.phone,
        accountNumber: row.accountNumber,
        isSingle: row.isSingle,
        sipid:row.sipid,
        products: this.productList.map(item => item.productName),
        adminUserId: row.adminUserId
      })
      this.roleAuth = Object.assign({}, this.roleAuth, {
        isOrder: row.isOrder,
        isProduct: row.isProduct,
        visibility: row.visibility,
      })
    },
    async getLowerRole() {
      const res = await fetchLowerRole()
      if (res.code === 1) {
        this.LowerRoleList = res.data
      }
    },
    clearForm() {
      this.form = Object.assign({}, this.form, {
        adminName: '',
        accountNumber: '',
        managerId: '',
        adminRole: null,
        phone: '',
        isSingle: 1,
        sipid:null,
        products: [],
      })
      this.roleAuth = Object.assign({}, this.roleAuth, {
        isOrder: 0,
        isProduct: 0,
        visibility: 0,
      })
      this.productList = []
      this.bindAppValue = ''
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    async selectRoleChange(value) {
      this.productList = []
      const role = this.LowerRoleList.filter(item => item.type === value)
      /*
      * visibility 判断是经理还是专员
      * */
      if (role[0].visibility === 1) {
        // 如果是专员 显示选择上级下拉框
        const res = await selectManagerUser({type: value})
        if (res.code === 1) {
          this.ManagerUserList = res.data
        }
      } else {
        // 如果是经理直接选择产品
        selectProduct({adminUserId: role[0].adminUserId, valid: 1}).then(res => {
          this.productList = res.data
        })
      }
      this.roleAuth = {
        isOrder: role[0].isOrder,
        isProduct: role[0].isProduct,
        visibility: role[0].visibility
      }
      this.$set(this.form, 'managerId', null)
    },
    async selectMangChange(value) {
      selectProduct({adminUserId: value, valid: 1}).then(res => {
        this.productList = res.data
      })
    },
    // 编辑/新增员工提交
    confirm() {
      this.$refs.form.validate(async v => {
        const products = []
        this.productList.forEach(item => {
          this.form.products.forEach(item2 => {
            if (item.productName === item2) {
              products.push(item)
            }
          })
        })
        if (v) {
          let obj = {
            accountNumber: this.form.accountNumber,
            adminName: this.form.adminName,
            adminRole: this.form.adminRole,
            isSingle: this.form.isSingle,
            phone: this.form.phone,
            sipid:this.form.sipid,
            products: products,
          }
          let api
          let message = ''
          if (this.visibleStaff.visibleType === 'add') {
            message = this.$t('新增成功')
            // 判断是否是专员
            if (this.roleAuth.visibility === 1) {
              obj.managerId = this.form.managerId
              obj.managerName = this.ManagerUserList.filter(item => item.adminUserId === this.form.managerId)[0].adminName
            }
            api = addSystemUser(obj)
          } else {
            message = this.$t('编辑成功')
            obj.adminUserId = this.form.adminUserId
            api = editSystemUser(obj)
          }
          const res = await api
          if (res.code === 1) {
            this.$message.success(this.$t(message))
            this.getTableData()
            this.clearForm()
            this.visibleStaff.visible = false
          }
        }
      })
    },
    // 批量绑定APP
    batchBindAPP() {
      selectProduct({status: 1, valid: 1}).then(res => {
        this.batchAPPList = res.data
      })
      this.batchBindVisible = true
    },
    async searchBatch() {
      if (!this.batchAPPName) return
      const res = await searchBindProduct({
        productName: this.batchAPPName,
        ...this.batchPage
      })
      if (res.code === 1) {
        const data = res.data
        const formatData = (list) => {
          return list.filter(item => {
            const children = list.filter(child => item.adminUserId === child.managerId)
            if (children.length > 0) {
              if (children.some(item => item.checked)) {
                item.checked = true
              }
              if (children.every(item => !item.checked)) {
                item.checked = false
              }
              item.children = children
            }
            return !item.managerId
          })
        }
        this.batchTableAllData = deepClone(data)
        this.batchTableData = formatData(res.data)
      }
    },
    formatData(list) {
      return list.filter(item => {
        const children = list.filter(child => item.adminUserId === child.managerId)
        if (children.length > 0) {
          item.children = children
        }
        return !item.managerId
      })
    },
    resetSearchBatch() {
      this.batchPage = {}
      this.searchBatch()
    },
    // 批量绑定app提交
    async batchConfirm() {
      const product = this.batchAPPList.find(item => item.productName === this.batchAPPName)
      const selectionRows = this.batchTableAllData.map(v => {
        v.productName = product.productName
        v.productId = product.productId
        return v
      })
      const res = await batchBindProduct(selectionRows)
      if (res.code === 1) {
        this.batchBindVisible = false
        this.$message.success(this.$t('操作成功'))
        this.$refs.table.$children[0].clearSelection()
        this.getTableData()
      }
    },
    rowAllCheckChange(value) {
      let data
      data = this.batchTableAllData.map(item => {
        return {
          ...item,
          checked: value
        }
      })
      this.batchTableAllData = data
      this.batchTableData = this.formatData(data)
    },
    rowCheckChange(value, row) {
      if (row.children && row.children.length) {
        // 父级勾选状态
        const setCheck = this.batchTableAllData.map(item => {
          if (row.children.some(val => val.adminUserId === item.adminUserId) || item.adminUserId === row.adminUserId) {
            item = {
              ...item,
              checked: value
            }
          }
          return item
        })
        this.batchTableAllData = setCheck
        this.batchTableData = this.formatData(setCheck)
      } else {
        this.toggleRowSelection(value, row)
        // 获取父级行
        const parentRow = this.batchTableData.find(item => {
          if (item.children && item.children.length) {
            return item.children.some(val => val.adminUserId === row.adminUserId)
          }
          return false
        })
        // 如果存在父级，父子级关联
        if (parentRow) {
          const nodeCheck = parentRow.children.every(item => item.checked)
          this.toggleRowSelection(nodeCheck, parentRow)
        }
      }
    },
    toggleRowSelection(checked, row) {
      const data = [...this.batchTableAllData].map(item => {
        if (item.adminUserId === row.adminUserId) {
          return {
            ...row,
            checked: checked
          }
        }
        return item
      })
      this.batchTableAllData = data
      this.batchTableData = this.formatData(data)
    },
    // 设置半勾选状态
    semiSelection(row) {
      let flag
      if (row.children && row.children.length) {
        // 子级有一个勾选就是半勾选
        const isCheck = row.children.some(item => item.checked)
        const isCheckAll = row.children.every(item => item.checked)
        if (isCheck && !isCheckAll) {
          flag = true
        } else {
          flag = false
        }
      }
      return flag
    },
    batchClose() {
      this.batchSelectRows = []
      this.batchAPPName = null
      this.batchTableData = []
      this.batchTableAllData = []
      this.batchPage = {}
    }
  },
  // beforeDestroy() {
  //   this.batchBindVisible = false
  // }
}
</script>

<style scoped>
</style>
